package cn.huaqingcheng.tianshu.common.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/**
 * HttpTool
 */
public class HttpTool {

    private static final HttpClient CLIENT = HttpClient.newBuilder()
            .priority(1)
            .executor(Runnable::run)
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(30))
            .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER))
            // .authenticator(Authenticator.getDefault())
            .followRedirects(HttpClient.Redirect.NORMAL)
            .build();


    public static HttpClient client() {
        return CLIENT;
    }

    /**
     * 下载文件
     *
     * @param uri 目标地址
     * @return 响应流, 消费者必须正确关闭
     * @throws IllegalStateException 任何 HTTP 错误
     */
    public static InputStream download(URI uri) {
        var request = HttpRequest.newBuilder()
                .GET()
                .uri(uri)
                .version(HttpClient.Version.HTTP_2)
                // .expectContinue(true)
                .build();

        try {
            HttpResponse<InputStream> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofInputStream());
            int code = response.statusCode();
            if (code >= 200 && code < 400) {
                return response.body();
            }

            throw new IllegalStateException(String.valueOf(code));
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
